#!/bin/bash

IMAGE_NAME=$1
TAG_NAME=$2

write_tag_ops(){

    IMAGE_TIME=$(date +%Y%m%d%H%M)
    ENV_TAG="${TAG_NAME##*_}"
    IMAGE_TAG="docker-reg.agtechcloud.com/app/$IMAGE_NAME:$TAG_NAME"
    BUILD_ENV=""
    OPS_ACCESS_KEY="2017033000"
    OPS_ACCESS_TOKEN="3UcUCb3xaEHK7kF2"

    OPS_HOST_URL=""
    if [[ "$ENV_TAG" == "daily" ]]; then
        BUILD_ENV="daily"
        OPS_HOST_URL="47.93.31.139:7001"
    elif [[ "$ENV_TAG" == "prepub" ]]; then
        BUILD_ENV="prepub"
        OPS_HOST_URL="47.93.31.139:7001"
    elif [[ "$ENV_TAG" == "publish" ]]; then
        BUILD_ENV="release"
        OPS_HOST_URL="47.93.31.139:7001"
    fi

        HTTP_CODE=0
    for k in $( seq 1 3 )
    do
        HTTP_CODE=`curl --connect-timeout 3 --max-time 5 -s -X PUT -H "accessKey: $OPS_ACCESS_KEY" -H "accessToken: $OPS_ACCESS_TOKEN" -H "Content-Type: application/json" -d "{\"image\":\"$IMAGE_TAG\",\"branch\":\"$BUILD_ENV\",\"version\":\"$TAG_NAME\",\"time\":\"$IMAGE_TIME\"}" http://$OPS_HOST_URL/build/api/packageResult/$IMAGE_NAME/$BUILD_ENV  -o /dev/null -w %{http_code}`
        echo $HTTP_CODE
        if [ $HTTP_CODE -eq 200 ]; then
          break
        fi
    done
    if [ $HTTP_CODE -ne 200 ]; then
      echo "[ERROR] write package info to ops failed."
      exit 1
    fi
}

deploy_docker(){
        echo "[deploy] building docker..."
        sudo docker build -t docker-reg.agtechcloud.com/app/$IMAGE_NAME:$TAG_NAME . || { echo "[ERROR] building docker failed"; exit 1; }

        echo "[deploy] pushing docker image to registry..."
        sudo docker login -u root -p A1b3987DF docker-reg.agtechcloud.com

        sudo docker push --disable-content-trust docker-reg.agtechcloud.com/app/$IMAGE_NAME:$TAG_NAME || { echo "[ERROR] pushing docker image failed" ; exit 1; }

        #write tag to ops
        echo "[deploy] writing tag to ops system..."
        write_tag_ops $IMAGE_NAME $TAG_NAME
}

cd "$(dirname "$0")"

deploy_docker

echo "[deploy] All Done, go to ops system to publish: http://47.93.31.139:7001/"